package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.ValidateCodeUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@RequestMapping("order")
public class OrderController {


    @Reference(version = "1.0.0")
    private OrderService orderService;


    @Resource
    private JedisPool jedisPool;

    /**
     * 随机生成验证码并发送短信到指定手机
     * @param telephone 手机号码
     * @return  发送的结果返回
     */
    @GetMapping("sendCode/{telephone}")
    public Result sendCode(@PathVariable String telephone){
        //生成手机验证码
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        System.out.println("手机验证码："+code);
        //将手机验证码存入redis中，失效时间5分钟
        Jedis resource = jedisPool.getResource();
        resource.setex("ORDER_"+telephone,5*60,code.toString());
        resource.close();
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    /**
     * 根据传入的预约订单信息进行添加预约操作
     * @param map   预约订单信息集合
     * @return  成功返回生成的订单编号，失败返回失败信息
     */
    @PostMapping("submit")
    public Result submit(@RequestBody Map<String, String> map){
        //获取验证码并与数据库进行比对
        String validateCode = map.get("validateCode");
        Jedis client = jedisPool.getResource();
        String code = client.get("ORDER_"+map.get("telephone"));
        if (code == null|| !code.equals(validateCode)){
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }
        //验证码验证通过，调用业务层添加方法
        Integer orderId = orderService.submit(map);
        return new Result(true,MessageConstant.ORDER_SUCCESS,orderId);
    }


    @RequestMapping("findById")
    public Result findById(int id){
        Map order = orderService.findById(id);
        return new Result(true,MessageConstant.ORDER_SUCCESS,order);
    }

    @RequestMapping("findFindOrder")
    public Result findFindOrder(@RequestBody Map<String, String> map){
        return orderService.findFindOrder(map);
    }

    @RequestMapping("mobileFindById/{id}")
    public Result mobileFindById(@PathVariable String id){
        Member member  = null;
        try {
            member = orderService.mobileFindById(id);
            return new Result(true,"查询成功!",member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询失败!");
        }

    }
}
